package com.ycfmedical.bed.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.CountDownTimer;
import android.os.IBinder;

import com.github.mikephil.charting.data.Entry;
import com.ycfmedical.bed.Constants;
import com.ycfmedical.bed.listener.IreceiveData;
import com.ycfmedical.bed.listener.IvsReplaceData;
import com.ycfmedical.bed.model.VsModel;
import com.ycfmedical.bed.listener.RefreshCallBack;
import com.ycfmedical.bed.utils.RefreshDataUtils;
import com.ycfmedical.bed.wifi.ClientThread;
import com.ycfmedical.bed.wifi.WifiEvent;

import java.util.ArrayList;

import cn.droidlover.xdroidmvp.log.XLog;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class VitalSignService extends Service implements IreceiveData, RefreshCallBack {

    private IvsReplaceData ivsReplaceData;
    private ArrayList<ArrayList<Entry>> lists;
    private ArrayList<Float> floatData;
    private ArrayList<Integer> Xmaxs;
    private boolean flag = true;
    private RefreshDataUtils refreshDataUtils;
    private String Weight_data;
    private CountDownTimer countDownTimer;
    private int num = 0;


    public class Mybinder extends Binder {
        public void setIvsReplacedata(IvsReplaceData ird) {
            ivsReplaceData = ird;
            ivsReplaceData.setServiceData(lists);
            ivsReplaceData.setText(Constants.BED_WEIGHT, Weight_data);
        }

        public void onUnbind() {
            ivsReplaceData = null;
        }
    }

    private Thread upData = new Thread() {
        @Override
        public void run() {
            super.run();
            while (flag) {
                //刷新数据
                try {
                    sleep(500);
                    notifyall(floatData);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    @Override
    public void receiveData(ArrayList<Float> data) {
        Timeout();
        // 数据来源
        for (int i = 0; i < data.size(); i++) {
            floatData.set(i, data.get(i));
            if (ivsReplaceData != null) {
                ivsReplaceData.setText(data);
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        createDataList(3);
        VsModel.getVsModel().setReceiveService(this);
        refreshDataUtils = RefreshDataUtils.getRefreshDataUtils();
        refreshDataUtils.register(this);
        upData.start();
        initTime();
    }

    private void initTime()
    {
        countDownTimer = new CountDownTimer(30*1000,1000)
        {
            @Override
            public void onTick(long millisUntilFinished)
            {

            }
            @Override
            public void onFinish()
            {
                //重连一次
                ClientThread.releaseLastSocket();
                WifiEvent wifi = WifiEvent.getInstance();
                wifi.getconnect(Constants.wifiIpAddressed,Constants.comPort);
                countDownTimer.start();
            }
        };
        Timeout();
    }
    /**
     * 超时，通知重新连接方法
     */
    private void Timeout() {
        countDownTimer.cancel();
        countDownTimer.start();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        flag = false;
        refreshDataUtils.remove(this);
    }

    /**
     * 数据绑定需要的方法
     */
    @Override
    public IBinder onBind(Intent intent) {
        return new Mybinder();
    }

    private void createDataList(int item) {
        //初始化容器
        floatData = new ArrayList<Float>();
        lists = new ArrayList<ArrayList<Entry>>();
        Xmaxs = new ArrayList<Integer>();

        Xmaxs.add(Constants.X_HEART_CONTENT);
        Xmaxs.add(Constants.X_BREATHE_CONTENT);
        Xmaxs.add(Constants.X_TEMPERATURE_CONTENT);

        for (int i = 0; i < item; i++) {
            lists.add(new ArrayList<Entry>());
        }
        floatData.add(0f);
        floatData.add(0f);
    }
    /**
     * 将数据刷新到表格方法
     * */
    private void upData(ArrayList<Float> data) {
        for (int i = 0; i < data.size(); i++) {
            if(i == 0){
                //刷新心率
                notifyHeart(data,i);
            }else if(i==1){
                //刷新呼吸
                notifyBreathe(data,i);
            }

            if (ivsReplaceData != null) {
                ivsReplaceData.replaceData(i);
            }
            floatData.set(i, 0f);
        }
    }
    //心率数据刷新方法
    private void notifyHeart(ArrayList<Float> data, int i) {

        ArrayList<Entry> entryData = lists.get(i);
        entryData.add(new Entry(lists.get(i).size(), data.get(i) + 10));
        //第二步：判断数据数量
        if (entryData.get(entryData.size() - 1).getX() == Xmaxs.get(i)) {
            lists.get(i).remove(0);
            //移除之前要先将容器里面所有的EntryX轴的数值减1
            for (int sign = 0; sign < entryData.size(); sign++) {
                Entry entry = entryData.get(sign);
                entry.setX(entry.getX() - 1);
                entry = null;
            }

        }
        entryData = null;
    }

    //呼吸数据刷新方法
    private void notifyBreathe(ArrayList<Float> data, int i) {

        ArrayList<Entry> entryData = lists.get(i);
        entryData.add(new Entry(lists.get(i).size(), data.get(i) + 10));

    //第二步：判断数据数量
        if (entryData.get(entryData.size() - 1).getX() > Xmaxs.get(i)) {
            lists.get(i).remove(0);
            //移除之前要先将容器里面所有的EntryX轴的数值减1
            for (int sign = 0; sign < entryData.size(); sign++) {
                Entry entry = entryData.get(sign);
                entry.setX(entry.getX() - 1);
                entry = null;
            }
        }
        entryData = null;
    }

    public void notifyall(ArrayList<Float> data) {
        rx.Observable.create(new rx.Observable.OnSubscribe<ArrayList<Float>>() {
            @Override
            public void call(Subscriber<? super ArrayList<Float>> subscriber) {
                subscriber.onNext(data);
            }
        }).onBackpressureDrop()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.immediate())
                .subscribe(new Subscriber<ArrayList<Float>>() {
                    @Override
                    public void onCompleted() {
                        //先判断再解除绑定
                        if (isUnsubscribed()) {
                            unsubscribe();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        XLog.e("SJH", e.toString());
                    }

                    @Override
                    public void onNext(ArrayList<Float> data) {
                        upData(data);
                        request(1);
                    }
                });
    }

    @Override
    public void setData(int flag, String data) {
        switch (flag) {
            case Constants.BED_TEMPERATURE:
                addTemperature(2, data);
                break;
            case Constants.BED_WEIGHT:
                Weight_data = data;
                if (ivsReplaceData != null) {
                    ivsReplaceData.setText(flag, data);
                }
                break;
            case Constants.BED_WIFE:
                if (ivsReplaceData != null) {
                   String state =  data.equals("true") ? "网络良好":"未连接";
                    ivsReplaceData.setText(flag, state);
                }
                break;
            default:
                break;
        }
    }
        /**
         * 添加刷新温度数据方法
         * */
    public void addTemperature (int Index, String data) {
        float number = Float.parseFloat(data);
        ArrayList<Entry> entryData = lists.get(Index);
        entryData.add(new Entry(lists.get(Index).size(), 8));
        entryData.add(new Entry(lists.get(Index).size(), number));
        if (entryData.get(entryData.size() - 1).getX() > Xmaxs.get(Index)) {

            //移除之前要先将容器里面所有的EntryX轴的数值减1
            for (int sign = 0; sign < lists.get(Index).size(); sign++) {
                Entry entry = lists.get(Index).get(sign);
                entry.setX(entry.getX() - 1);
                entry = null;
            }
            lists.get(Index).remove(0);
        }
        if (ivsReplaceData != null) {
            ivsReplaceData.setText(Constants.BED_TEMPERATURE, data);
            ivsReplaceData.replaceData(Index);
        }
    }
}
